package com.zhike.service.system.impl;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.zhike.common.constant.SysConfigConstants;
import com.zhike.common.dto.WebhookDTO;
import com.zhike.common.model.Webhook;
import com.zhike.common.vo.WebhookVO;
import com.zhike.mapper.system.WebhookMapper;
import com.zhike.service.system.ISystemConfigService;
import com.zhike.service.system.IWebhookService;

import cn.hutool.core.util.IdUtil;

@Service
public class WebhookServiceImpl implements IWebhookService {

    @Resource
    private WebhookMapper webhookMapper;

    @Autowired
    private ISystemConfigService systemConfigService;

    @Override
    public WebhookVO create(WebhookDTO dto) {
        Webhook model = new Webhook();
        String domain = systemConfigService.getValueByKey(SysConfigConstants.CONFIG_TYPE_IM,
                SysConfigConstants.CONFIG_FILE_DOMAIN, "http://localhost");
        if (StringUtils.isNotBlank(domain)) {
            String webhookId = IdUtil.randomUUID();
            model.setWebhookId(webhookId);
            model.setAddr(domain + "/api/zkim/v1/hook/" + webhookId);
            model.setSecretKey(IdUtil.objectId());
            model.setGroupId(dto.getGroupId());
        }
        if (webhookMapper.insert(model) > 0) {
            WebhookVO vo = new WebhookVO();
            vo.setAddr(model.getAddr());
            return vo;
        }
        return null;
    }

    @Override
    public Webhook getWebhook(String webhookId) {
        LambdaQueryWrapper<Webhook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Webhook::getWebhookId, webhookId);
        lqw.eq(Webhook::getStatus, "0");
        return webhookMapper.selectOne(lqw);
    }

}
